<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :fullscreen.sync="fullscreen"
    @cancel="handleCancel"
    :footer="null"
  >
    <a-card :bordered="false">
      <detail-list title="单据信息">
        <detail-list-item term="单据状态">
          <!-- 单据状态：new新建 approve申请 audit_pass通过 audit_refuse不通过 invalid作废  -->
          <a-tag color="orange" v-if="model.bizStatus == 'approve'">待审核</a-tag>
          <a-tag color="blue" v-if="model.bizStatus == 'audit_pass'">审核通过</a-tag>
          <a-tag color="orange" v-if="model.bizStatus == 'audit_refuse'">审核不通过</a-tag>
        </detail-list-item>
        <detail-list-item term="单号">{{ model.billNo }}</detail-list-item>
        <detail-list-item term="门店">{{ model.orgName }}/{{ model.shopName }}</detail-list-item>
        <detail-list-item term="经办人">{{ model.bizUserName }}</detail-list-item>
        <detail-list-item term="盘点时间">{{ model.bizDate }}</detail-list-item>
        <detail-list-item term="备注">{{ model.remark ? model.remark : '-' }}</detail-list-item>
      </detail-list>
      <template v-if="!isView">
        <a-divider style="margin-bottom: 32px" />
        <detail-list title="审核">
          <a-spin :spinning="confirmLoading">
            <a-form-model ref="form" :model="auditModel" :rules="validatorRules">
              <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bizStatus" label="审核意见">
                <a-select v-model="auditModel.bizStatus">
                  <a-select-option value="audit_pass">通过</a-select-option>
                  <a-select-option value="audit_refuse">不通过</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark" label="备注">
                <a-textarea :rows="4" placeholder="最多支持500个字" :maxlength="500" v-model="auditModel.remark" />
              </a-form-model-item>
              <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
                <a-button type="primary" html-type="submit" @click="handleOk"> 审核 </a-button>
              </a-form-item>
            </a-form-model>
          </a-spin>
        </detail-list>
      </template>
      <template v-else>
        <a-divider style="margin-bottom: 32px" />
        <detail-list title="审核信息">
          <detail-list-item term="审核时间"> {{ model.auditDate }} </detail-list-item>
          <detail-list-item term="审核意见"> {{ model.auditRemark ? model.auditRemark : '-' }} </detail-list-item>
        </detail-list>
      </template>
    </a-card>
    <!-- 明细 -->
    <a-card
      :bordered="false"
      :tabList="tabList"
      :activeTabKey="activeTabKey"
      @tabChange="
        (key) => {
          this.activeTabKey = key
        }
      "
    >
      <span :key="index" v-for="(current, index) in posStockCheckChilds">
        <detail-list title="子盘单信息" v-if="activeTabKey === index + '' && index > 0">
          <detail-list-item term="名称">{{ current.name }}</detail-list-item>
          <detail-list-item term="子盘单总件数">{{ current.totalQty }}</detail-list-item>
          <detail-list-item term="备注">{{ current.remark }}</detail-list-item>
        </detail-list>
        <detail-list v-if="activeTabKey === index + '' && index === 0">
          <detail-list-item term="说明">全部商品=盘点商品+未盘商品 , 不含异常商品</detail-list-item>
          <detail-list-item term="盘点总件数">{{ totalQty }}</detail-list-item>
        </detail-list>
        <s-table
          size="middle"
          v-if="activeTabKey == index + ''"
          :columns="groupColumns"
          :data="loadCheckGoods"
          :pagination="false"
          :scroll="{ y: 500 }"
        >
          <a-table
            style="margin: 1px"
            slot="expandedRowRender"
            slot-scope="record"
            :columns="goodsColumns"
            :dataSource="record.list"
            size="small"
            rowKey="id"
            bordered
            :pagination="false"
            :scroll="{ y: 1000 }"
          >
            <span slot="photo" slot-scope="text">
              <a-avatar
                shape="square"
                :src="text + '?x-oss-process=image/resize,w_50,h_50'"
                @click="text ? previewImgObject([text]) : () => {}"
              >
              </a-avatar>
            </span>
          </a-table>
        </s-table>
      </span>
    </a-card>
  </j-modal>
</template>

<script>
import PageLayout from '@/components/page/PageLayout'
import STable from '@/components/table/'
import DetailList from '@/components/tools/DetailList'
import ABadge from 'ant-design-vue/es/badge/Badge'
import { postAction } from '@/api/manage'
import { Modal } from 'ant-design-vue'
import { groupingData } from '@/utils/util'
import Template1 from '../../jeecg/JVxeDemo/layout-demo/Template1.vue'
const DetailListItem = DetailList.Item
import { previewImgObject } from '@/utils/util'

export default {
  components: {
    PageLayout,
    ABadge,
    DetailList,
    DetailListItem,
    STable,
    Template1,
  },
  name: 'PosStockCheckModal',
  data() {
    return {
      title: '操作',
      isView: false,
      fullscreen: true,
      visible: false,
      id: '',
      previewImgObject,
      groupingData,
      params: {},
      model: {},
      auditModel: {},
      totalQty: 0,
      posStockCheckChilds: [],
      checkGoodsList: [],
      groupDataList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      tabList: [
        // {
        //   key: '1',
        //   tab: '子盘单',
        // },
        // {
        //   key: '2',
        //   tab: '子盘1单',
        // },
      ],
      activeTabKey: '0',
      confirmLoading: false,
      validatorRules: {
        bizStatus: { required: true, message: '必填项' },
      },
      groupColumns: [
        {
          title: '价位',
          align: 'left',
          dataIndex: 'markPrice',
        },
        {
          title: '件数',
          align: 'left',
          dataIndex: 'cnt',
          customRender: (text, record) => {
            return record.list.reduce((total, cur) => {
              return total + cur.checkQty
            }, 0)
          },
        },
      ],
      goodsColumns: [
        {
          title: '商品图片',
          align: 'center',
          dataIndex: 'photo',
          scopedSlots: { customRender: 'photo' },
        },
        {
          title: 'SKU编码',
          align: 'center',
          dataIndex: 'itemSku',
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'itemShortName',
        },
        {
          title: '颜色',
          align: 'center',
          dataIndex: 'itemColor',
        },
        {
          title: '尺码',
          align: 'center',
          dataIndex: 'itemSize',
        },
        {
          title: '零售单价(元)',
          align: 'center',
          dataIndex: 'markPrice',
        },
        {
          title: '盘时库存->盘点数量',
          align: 'center',
          dataIndex: 'ioQty',
          customRender: (text, current) => {
            return current.ioQty + ' -> ' + current.checkQty
          },
        },
        {
          title: '盈亏数量',
          align: 'center',
          dataIndex: 'res',
          customRender: (text, current) => {
            return current.checkQty - current.ioQty
          },
        },
        {
          title: '盈亏金额(元)',
          align: 'center',
          dataIndex: 'resMoney',
          customRender: (text, current) => {
            return (current.checkQty - current.ioQty) * current.markPrice
          },
        },
      ],
      url: {
        detail: '/stock/check/posStockCheck/getCheckDetail',
        checkIt: '/stock/check/posStockCheck/checkIt',
        previewAll: '/stock/check/posStockCheck/preview',
        detailChild: '/stock/check/posStockCheckChild/checkChildList',
        detailChildGoods: '/stock/check/posStockCheckChild/getCheckChildDetail',
      },
    }
  },
  created() {},
  methods: {
    clear() {
      this.model = {}
      this.auditModel = {}
      this.posStockCheckChilds = []
      this.activeTabKey = '0'
      this.tabList = []
    },
    view(record) {
      this.detail(record)
      this.visible = true
    },
    close() {
      this.$emit('close')
      this.clear()
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    detailChild(checkBillId) {
      return postAction(this.url.detailChild + '/' + checkBillId, {})
    },
    previewAll(billId) {
      let that = this
      return postAction(this.url.previewAll + '/' + billId, {}).then((res) => {
        if (res.success) {
          let checkGoodsList = res.result
          let mapDataList = that.groupingData(checkGoodsList, 'markPrice')
          mapDataList.sort((a, b) => {
            return a.markPrice - b.markPrice
          })
          console.log('mapDataList', mapDataList)
          that.totalQty = that.sumQty(checkGoodsList)
          return { data: mapDataList }
        }
        return { data: [] }
      })
    },
    sumQty(arr) {
      let sum = 0
      arr.forEach(function (val) {
        sum += val.checkQty
      })
      console.log(sum)
      return sum
    },
    detailChildGoods(childBillId) {
      let that = this
      return postAction(this.url.detailChildGoods + '/' + childBillId, {}).then((res) => {
        if (res.success) {
          let checkGoodsList = res.result.checkGoodsList
          let mapDataList = that.groupingData(checkGoodsList, 'markPrice')
          mapDataList.sort((a, b) => {
            return a.markPrice - b.markPrice
          })
          console.log('mapDataList', mapDataList)
          return { data: mapDataList }
        }
        return { data: [] }
      })
    },
    detail(record) {
      let that = this
      this.id = record.checkBillId
      postAction(this.url.detail + '/' + this.id, this.params).then(async (res) => {
        if (res.success) {
          this.model = Object.assign({}, res.result, record)
          let resDetail = await this.detailChild(this.id)
          if (resDetail.success) {
            let posStockCheckChilds = resDetail.result
            let newPosStockCheckChilds = []
            let len = posStockCheckChilds.length
            if (len <= 2) {
              newPosStockCheckChilds = posStockCheckChilds
            } else {
              for (var i = 2; i < len; i++) {
                newPosStockCheckChilds.push(posStockCheckChilds[i])
              }
              newPosStockCheckChilds.push(posStockCheckChilds[0])
              newPosStockCheckChilds.push(posStockCheckChilds[1])
            }

            let allProdChild = { id: 0, name: '全部商品' }
            newPosStockCheckChilds.unshift(allProdChild)

            newPosStockCheckChilds.forEach((current, index) => {
              this.tabList.push({ key: index + '', tab: current.name })
            })
            this.posStockCheckChilds = newPosStockCheckChilds
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    loadCheckGoods() {
      console.log('activeTabKey', this.activeTabKey)
      if (this.activeTabKey > 0) {
        let checkChild = this.posStockCheckChilds[this.activeTabKey]
        return this.detailChildGoods(checkChild.id)
      } else {
        return this.previewAll(this.model.checkBillId)
      }
    },

    handleOk() {
      const that = this
      this.auditModel.checkId = this.id
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (that.auditModel.bizStatus === 'audit_refuse' && !that.auditModel.remark) {
            that.$message.warning('审批不通过时备注必填')
            return false
          }
          if (that.auditModel.bizStatus === 'audit_pass') {
            Modal.confirm({
              title: '审核通过将会根据盘点结果调整库存，继续操作吗?',
              okText: '确定',
              okType: 'danger',
              cancelText: '取消',
              onOk() {
                console.log('OK')
                that.doAdudit(that.auditModel)
              },
              onCancel() {
                console.log('Cancel')
              },
            })
          } else {
            that.doAdudit(that.auditModel)
          }
        } else {
          return false
        }
      })
    },

    doAdudit(auditModel) {
      this.confirmLoading = true
      postAction(this.url.checkIt, auditModel)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
          this.close()
        })
    },
  },
}
</script>

<style lang="less" scoped>
.title {
  color: rgba(0, 0, 0, 0.85);
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}
</style>